var express = require('express');
var router = express.Router();
var package = require("../package.json");
var dbHelper = require("../app_modules/mongoHelper.js");
var tool = require("../app_modules/tools.js");
var fs = require('fs');

var multiparty = require('multiparty');
router.post('/upload', function (req, res, next) {
   var form = new multiparty.Form({ uploadDir: package.filePath});    
   form.parse(req, function (err, fields, files) {
        if(files.inputFile==undefined){
           res.send({status:"0",msg:"upload faild,the files is requried.",metadata:{}});
        }
        else if(!err){
            var MetaData=[];
            var url=package.apiUrl+package.filePath.replace("./public/","");
            
            for(i=0;i<files.inputFile.length;i++){
                var file = files.inputFile[i];                   
                var OriginalFile=file.originalFilename;
                var index=OriginalFile.lastIndexOf(".");
                var fileName = OriginalFile.substring(0, index);
                var fileType = OriginalFile.substring(index + 1, OriginalFile.length); 
                //new file name
	              var newFileName=fileName+"_myfile_"+tool.Gettimestamp()+"."+fileType;              
                MetaData.push({"index":i,"fileName":newFileName,"href":url+newFileName});
                saveFile(file,newFileName,fileType,function(){
                   fs.rename(file.path,package.filePath + newFileName);
                });                
              }
            return res.send({status:"1",msg:"upload successfully.",metadata:MetaData});
           }
        else
        {
           return res.send({status:"0",msg:"upload error.",metadata:{}});
        }
       });
});

function saveFile (inputFile,newFileName,fileType,callback){ 
   return callback();
  // fileType=fileType.toLowerCase();
  // var dirpath=package.filePath; 
  // //if(package.imgType.indexOf(fileType)>=0){
  // if(true){
  //     var images = require("images");
  //     var sourceImg = inputFile.path; 
  //     var imgSize=package.imgSize;
  //     for(g=0;g<imgSize.length;g++){
  //       var newPath=dirpath+imgSize[g].toString()+"px/";
  //       if (!fs.existsSync(newPath)) {
  //           fs.mkdirSync(newPath);k
  //       }
  //       images(sourceImg).resize(imgSize[g])
  //       .save(dirpath + newFileName, {});
  //     }          
  //     return callback();
  // }
  // else 
  // fs.readFile(inputFile.path, 'utf8', function(err, data){
  //   console.log(data);  
  //   return callback();
  // });

  // var fs = require("fs");
  // var data = '';
  // var readerStream = fs.createReadStream(inputFile.path);
  // readerStream.setEncoding('UTF8'); 
  // readerStream.on('data', function(chunk) {
  //   data += chunk;
  // });
  // readerStream.on('end',function(){   
  //   dbHelper.create("file",{"name":newFileName,"type":fileType,"data":data,"createData":new Date()},function(response){
  //   })
  //   return callback();
  // });
}

router.post('/deleteFile', function (req, res, next) {
  var filename=tool.getObj(req.body.filename,"");
  if(filename==""){
    return res.send({status:"0",msg:"filename is Required",metadata:{}});
  }
  else{      
    //  var imgSize=appConfing.getImsSize();
    //  for(sg=0;sg<imgSize.length;sg++){
    //   fs.unlinkSync("./public/files/upload/" + imgSize[sg].toString()+filename);
    //  }     
     fs.unlinkSync(package.filePath + filename);
     return res.send({status:"1",msg:"the files has deleted",metadata:{}});
  }  
});

module.exports = router;